<template>
  <div class="zh-classTime-setting">
    <nav-header></nav-header>
    <div class="zh-table">
      <div class="zh-table-open clear">
        <div class="zh-open-left fl">
          <div class="open-width" style="width: 400px">
            <!-- <el-date-picker v-model="listParam.time" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm"
              type="datetime" placeholder="选择日期时间">
            </el-date-picker> -->
            <el-date-picker
              v-model="dataTime"
              type="datetimerange"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
              :picker-options="pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
            >
            </el-date-picker>
          </div>
          <div class="open-width" style="width: 145px">
            <el-cascader
              placeholder="请选择班级"
              :options="orgDatas"
              :props="orgDataProps"
              v-model="selectedOrgOptions"
            >
            </el-cascader>
          </div>
          <div class="open-width" style="width: 145px">
            <div class="open-width" style="width: 145px">
              <el-select
                v-model="listParam.teacher_id"
                filterable
                placeholder="请选择教师"
              >
                <el-option
                  v-for="item in teacherArr"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="open-width" style="width: 145px">
            <el-select
              v-model="listParam.subject_id"
              filterable
              placeholder="请选择科目"
            >
              <el-option
                v-for="item in subjectArr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
          <el-button type="primary" @click="searchFunc">查询</el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </div>
        <div class="zh-open-right fr">
          <el-button type="primary" @click="openSetting">考勤设置</el-button>
          <el-button type="primary" @click="handExcel()">导出数据</el-button>
        </div>
      </div>

      <div
        class="zh-table-contents"
        v-loading="loading.status"
        :element-loading-text="loading.txt"
      >
        <el-table
          :data="listData"
          @selection-change="tableSelectionChange"
          border
          max-height="600"
          style="width: 100%"
        >
          <el-table-column
            type="index"
            :index="typeIndex"
            label="序号"
            align="center"
            show-overflow-tooltip
            width="50"
          >
          </el-table-column>
          <el-table-column
            prop="course_time"
            label="上课时间"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="subject_name"
            label="上课科目"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="class_name"
            label="上课班级"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="teacher_name"
            label="授课老师"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="all_num"
            label="应到人数"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="all_reality_num"
            label="实到人数"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="late_num"
            label="迟到人数"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="leave_num"
            label="请假人数"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="early_num"
            label="早退人数"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="lack_num"
            label="缺勤人数"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>

          <el-table-column
            prop="5"
            label="操作"
            align="center"
            width="100"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-button @click="lookOver(scope.row)" type="text"
                >查看</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="table-pagination" v-show="total_number > 10">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="listParam.page_index"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size="listParam.page_size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total_number"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- 添加课时 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      title="考勤设置"
      :visible.sync="setDialog"
      class="classHour"
      width="590px"
    >
      <el-form
        :model="setform"
        ref="setform"
        :rules="rules"
        status-icon
        label-position="left"
      >
        <el-form-item label="迟到">
          <el-radio v-model="setform.late_status" label="1">开启</el-radio>
          <el-radio v-model="setform.late_status" label="0">关闭</el-radio>
        </el-form-item>
        <el-form-item label="上课后晚于" prop="late_min">
          <el-select
            :disabled="setform.late_status == '0'"
            v-model="setform.late_min"
            placeholder="请选择"
            style="width: 160px"
          >
            <el-option
              v-for="item in lateOptionsTimes"
              :key="item.value"
              :label="item.value"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <span>分钟识别人脸记为迟到</span>
        </el-form-item>
        <el-form-item label="早退">
          <el-radio v-model="setform.early_status" label="1">开启</el-radio>
          <el-radio v-model="setform.early_status" label="0">关闭</el-radio>
        </el-form-item>
        <el-form-item label="已到勤学生，下课前" prop="early_min">
          <el-select
            :disabled="setform.early_status == '0'"
            v-model="setform.early_min"
            placeholder="请选择"
            style="width: 160px"
          >
            <el-option
              v-for="item in optionsTimes"
              :key="item.value"
              :label="item.value"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <span>内分钟一直没有识别人脸记为早退</span>
        </el-form-item>
        <el-form-item label="缺勤">
          <el-radio v-model="setform.absence_status" label="1">开启</el-radio>
          <el-radio v-model="setform.absence_status" label="0">关闭</el-radio>
        </el-form-item>
        <el-form-item label="上课后 " prop="absence_min">
          <el-select
            :disabled="setform.absence_status == '0'"
            v-model="setform.absence_min"
            placeholder="请选择"
            style="width: 160px"
          >
            <el-option
              v-for="item in lackOptionsTimes"
              :key="item.value"
              :label="item.value"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <span>分钟内一直没有识别人脸记为缺勤</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="setDialog = false">取消</el-button>
        <el-button type="primary" @click="saveSet">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      total_number: 0,
      selectedOrgOptions: [],
      initFuncNum: 4,
      orgDatas: [],
      orgParam: {
        data_type: "manage_tree",
        status: [1, 2],
      },
      orgDataProps: {
        value: "id",
        label: "name",
      },
      orgData: [],
      loading: {
        status: false,
        txt: "获取数据...",
      },
      listData: [{ id: 1 }],
      setDialog: false,
      setform: {
        late_status: "0", //迟到，0：关闭，1：开启
        late_min: null,
        early_status: "0", //早退，0：关闭，1：开启
        early_min: null,
        absence_status: "0", //缺勤，0：关闭，1：开启
        absence_min: null,
      },
      showLate: false,
      showLeave: false,
      showAbsent: false,
      section: "",
      rangTime: [],
      rules: {
        late_min: [
          { validator: this.validateTime, trigger: "blur", required: true },
        ],
        early_min: [
          { validator: this.validateTime, trigger: "blur", required: true },
        ],
        absence_min: [
          { validator: this.validateTime, trigger: "blur", required: true },
        ],
      },
      timeLimit: {
        startTimeMinTime: "00:00",
        startTimeMaxTime: "24:00",
        endTimeMinTime: "00:00",
        endTimeMaxTime: "24:00",
      },
      tempInx: -1,
      title: "",
      selected: [],
      sectionInx: 0,
      classArr: [], //班级下拉框
      teacherArr: [], //教师下拉框
      subjectArr: [{ id: null, name: "全部科目" }], //科目下拉框
      // 条件筛选
      listParam: {
        class_id: null,
        subject_id: null,
        teacher_id: null,
        page_index: 1,
        page_size: 10,
      },
      dataTime: [],
      lateOptionsTimes: [
        {
          value: 5,
        },
        {
          value: 10,
        },
        {
          value: 20,
        },
      ],
      optionsTimes: [
        {
          value: 5,
        },
        {
          value: 10,
        },
        {
          value: 20,
        },
        {
          value: 30,
        },
      ],
      lackOptionsTimes: [
        {
          value: 30,
        },
        {
          value: 35,
        },
        {
          value: 40,
        },
        {
          value: 45,
        },
      ],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getClassData();
    this.getTeacherData();
    this.getSubjectData();
    this.getOrgData();
  },
  watch: {
    "setform.late_status": function (val) {
      if (val === "0") {
        this.setform.late_min = null;
        this.showLate = true;
      } else {
        this.showLate = false;
        this.setform.late_min = 5;
      }
    },
    "setform.early_status": function (val) {
      if (val === "0") {
        this.setform.early_min = null;
        this.showLeave = true;
      } else {
        this.showLeave = false;
        this.setform.early_min = 5;
      }
    },
    "setform.absence_status": function (val) {
      if (val === "0") {
        this.setform.absence_min = null;
        this.showAbsent = true;
      } else {
        this.showAbsent = false;
        this.setform.absence_min = 30;
      }
    },
    setDialog() {
      if (this.setDialog === false) {
        this.$refs.setform.clearValidate();
        this.setform = {
          late_status: "1", //迟到，0：关闭，1：开启
          late_min: 5,
          early_status: "1", //早退，0：关闭，1：开启
          early_min: 5,
          absence_status: "1", //缺勤，0：关闭，1：开启
          absence_min: 30,
        };
      }
    },
    initFuncNumFinal: {
      handler(newVal, oldVal) {
        if (parseInt(newVal) === this.initFuncNum) {
          this.getList();
        }
      },
      deep: true,
    },
    selectedOrgOptions: {
      handler(newVal, oldVal) {
        console.log(newVal, oldVal);
        this.listParam.class_id = newVal[newVal.length - 1];
      },
      deep: true,
    },
  },
  methods: {
    /**
     * 序号
     */
    typeIndex(index) {
      return (
        index + (this.listParam.page_index - 1) * this.listParam.page_size + 1
      );
    },
    getOrgData() {
      // 获取组织架构
      if (this.$store.state.checkLevel) {
        this.orgParam.direction = "down";
        this.orgParam.data_type = "manage_tree";
        this.orgParam.pid = 1;
      }
      // 重写成功回调
      let success = (data) => {
        this.orgData = data.data;
        console.log(data.data[0].children);
        let dataN = [];
        data.data[0].children.forEach((item) => {
          // console.log('---item', item)
          item.children.forEach((item2) => {
            dataN.push(item2);
          });
        });
        console.log(dataN);
        this.orgDatas = this.getTreeData(dataN, 4);
        // console.log('orgDatas---', this.orgDatas)
        this.$forceUpdate(); //强制渲染
        this.initFuncNumFinal++;
      };
      if (this.$store.state.checkLevel) {
        this.$ajax.get("api/newlevel/platform_org", {
          params: this.orgParam,
          func: { success: success },
        });
      } else {
        this.$ajax.get("api/org/org", {
          params: this.orgParam,
          func: { success: success },
        });
      }
    },

    // 递归遍历将多层嵌套数组里最里的空children数组的值改为undefined
    getTreeData(data, level) {
      // 循环遍历json数据
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          if (data[i].level == level) data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children, level);
        }
      }
      return data;
    },
    /**
     * 验证整数
     */
    validateTime(rule, value, callback) {
      if (rule.field === "late_min" && this.setform.late_status === "1") {
        if (this.setform.late_min === "" || this.setform.late_min === null) {
          return callback(new Error("请选择"));
        }
      }
      if (rule.field === "early_min" && this.setform.early_status === "1") {
        if (this.setform.early_min === "" || this.setform.early_min === null) {
          return callback(new Error("请选择"));
        }
      }
      if (rule.field === "absence_min" && this.setform.absence_status === "1") {
        if (
          this.setform.absence_min === "" ||
          this.setform.absence_min === null
        ) {
          return callback(new Error("请选择"));
        }
      }
      callback();
    },
    saveSet() {
      this.$refs.setform.validate((valid) => {
        if (valid) {
          // 保存
          let success = (data) => {
            this.$message.success(data.msg);
            this.setDialog = false;
            this.getList();
          };
          this.$ajax.put("api/ainew/attendRule", this.setform, {
            func: { success: success },
          });
        } else {
          return false;
        }
      });
    },

    tableSelectionChange(vals) {
      this.selected = vals;
    },

    // 导出数据
    handExcel() {
      if (this.listData.length === 0) {
        this.$message.warning("导出数据为空");
        return false;
      }
      let _id = [];
      this.selected.forEach((item) => {
        _id.push(item.id);
      });
      if (!is_empty(this.dataTime)) {
        this.listParam.start_time = this.dataTime[0];
        this.listParam.end_time = this.dataTime[1];
      } else {
        this.listParam.start_time = "";
        this.listParam.end_time = "";
      }
      let params = {
        attend_id: _id,
        ...this.listParam,
      };
      // fix
      this.export_excel("api/ainew/attendListExcel", params, "考勤报表数据");
    },
    // 获取班级下拉框
    getClassData() {
      let success = (res) => {
        this.classArr = res.data;
        this.classArr.unshift({ id: null, rename: "全部班级" });
      };
      this.$ajax.get("api/newlevel/platform_org", {
        params: { level: 4, direction: "down" },
        func: { success },
      });
    },
    // 获取教师下拉框
    getTeacherData() {
      let success = (res) => {
        this.teacherArr = res.data;
        this.teacherArr.unshift({ id: null, name: "全部教师" });
      };

      this.$ajax.get("api/user/user", { func: { success: success } });
    },
    // 获取科目下拉框
    getSubjectData() {
      let success = (res) => {
        this.subjectArr = res.data;
        this.subjectArr.unshift({ id: null, name: "全部科目" });
      };

      this.$ajax.get("api/cate/subject", { func: { success: success } });
    },
    // 查看考勤详情
    lookOver(row) {
      //
      this.$router.push("/affairs/attend/attendance-details/" + row.attend_id);
    },

    getList() {
      this.loading.status = true;
      // 重写成功回调
      let success = (data) => {
        this.loading.status = false;
        this.listData = data.data.data;
        this.total_number = data.data.data_sum;

        // this.$forceUpdate(); //强制渲染
      };
      let fail = (data) => {
        this.loading.status = false;
        this.$message.error(data.msg);
      };
      if (!is_empty(this.dataTime)) {
        this.listParam.start_time = this.dataTime[0];
        this.listParam.end_time = this.dataTime[1];
      } else {
        this.listParam.start_time = "";
        this.listParam.end_time = "";
      }
      let params = {
        ...this.listParam,
      };
      //todo api
      this.$ajax.get("api/ainew/attendList", {
        // this.$ajax.get("api/school/timeset", {
        params: params,
        func: { success: success, fail: fail },
      });
    },
    handleSizeChange(val) {
      this.listParam.page_index = 1;
      this.listParam.page_size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listParam.page_index = val;
      this.getList();
    },
    searchFunc() {
      this.listParam.pageIndex = 1;
      this.getList();
    },
    reset() {
      this.listParam = {
        class_id: null,
        subject_id: null,
        teacher_id: null,
        start_time: null,
        end_time: null,
      };
      this.dataTime = [];
      this.getList();
    },
    openSetting() {
      let success = (res) => {
        this.setform = res.data;
        this.setform = {
          late_status: res.data.late_status ? "1" : "0", //迟到，0：关闭，1：开启
          late_min: res.data.late_min
            ? res.data.late_min
            : res.data.late_status
            ? 5
            : null,
          early_status: res.data.early_status ? "1" : "0", //早退，0：关闭，1：开启
          early_min: res.data.early_min
            ? res.data.early_min
            : res.data.early_status
            ? 5
            : null,
          absence_status: res.data.absence_status ? "1" : "0", //缺勤，0：关闭，1：开启
          absence_min: res.data.absence_min
            ? res.data.absence_min
            : res.data.absence_status
            ? 30
            : null,
        };

        this.setDialog = true;
      };
      this.$ajax.get("api/ainew/attendRule", { func: { success: success } });
    },
  },
};
</script>
<style lang="scss">
.zh-classTime-setting {
  .el-table__body-wrapper table tbody {
    td:nth-child(4) {
      padding: 0;
    }
  }

  .classHour {
    .el-form-item__content {
      .el-date-editor {
        width: 100%;
      }
    }
  }
}
</style>
